from flask import Blueprint, render_template, request, session
from flask_login import login_required, current_user
from sqlalchemy import desc
from applications.common.curd import model_to_dicts, enable_status, disable_status, get_one_by_id
from applications.common import curd
from applications.common.curd import enable_status, disable_status
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import str_escape
from applications.extensions import db
from applications.models import Violation
from applications.models import Fraction


admin_fraction = Blueprint('adminFraction', __name__, url_prefix='/admin/fraction')


# 用户管理
@admin_fraction.get('/')
@authorize("admin:fraction:main")
def main():

    return render_template('admin/fraction/main.html')


# 表格数据
@admin_fraction.get('/data')
@authorize("admin:fraction:main")
def table():
    username = str_escape(request.args.get('username', type=str))
    filters = []
    if username:
        filters.append(Fraction.username.contains(username))
    fraction = Fraction.query.filter(*filters).layui_paginate()
    # return table_api(data=roles.items, count=roles.total)
    return table_api(
        data=[{
            'id': Fraction.id,
            'cate': Fraction.cate,
            'num': Fraction.num,
            'username': Fraction.username,
            'user_id': Fraction.user_id,
            'sort': Fraction.sort,
            'create_time': Fraction.create_time,
        } for Fraction in fraction.items],
        count=fraction.total)

@admin_fraction.delete('/remove/<int:id>')
@authorize("admin:fraction:remove", log=True)
def remove(id):
    r = Fraction.query.filter_by(id=id).delete()
    db.session.commit()
    if not r:
        return fail_api(msg="删除失败")
    return success_api(msg="删除成功")


# 批量删除
@admin_fraction.delete('/batchRemove')
@authorize("admin:fraction:remove", log=True)
def batch_remove():
    ids = request.form.getlist('ids[]')
    for id in ids:
        r = Fraction.query.filter_by(id=id).delete()
        db.session.commit()
    return success_api(msg="批量删除成功")
